package com.guaoran.distributed.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : 孤傲然
 * @description : 启动类
 * @date :2019/11/2 14:27
 */
@SpringBootApplication
@RestController
public class SentinelDemoApplication {
    public static void main(String[] args) {
        initFlowRules();
        SpringApplication.run(SentinelDemoApplication.class,args);
    }
    // -Dcsp.sentinel.dashboard.server=localhost:8888 -Dproject.name=sentinel-dashboard-aop

    //初始化规则
    private static void initFlowRules(){
        List<FlowRule> rules=new ArrayList<>(); //限流规则的集合
        FlowRule flowRule=new FlowRule();
        flowRule.setResource("sayHello");//资源(方法名称、接口）
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS); //限流的阈值的类型
        flowRule.setCount(10);
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }

    @SentinelResource(value = "sayHello") //针对方法级别的限流
    @GetMapping("/say")
    public String sayHello(){
        System.out.println("hello world");
        return "hello world";
    }
    @Bean
    public SentinelResourceAspect sentinelResourceAspect(){
        return new SentinelResourceAspect();
    }

}
